package com.orm.config;

import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@Data
public class JdbcTemplateConfig implements ApplicationListener<ApplicationReadyEvent> {

    @Resource
    ApplicationContext applicationContext;

    @Bean
    @ConditionalOnBean(DataSource.class)
    @ConditionalOnMissingBean(JdbcTemplate.class)
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        JdbcTemplate bean = applicationContext.getBean(JdbcTemplate.class);
        System.out.println("jdbcTemplate = " + bean);
        System.out.println("JdbcTemplateConfig onApplicationEvent:开始缓存jdbcTemplate") ;
        JdbcCache.setJdbcTemplate(bean);
    }
}
